"""
客户模型
"""
from sqlalchemy import Column, Integer, String, Text, DateTime, DECIMAL
from sqlalchemy.orm import relationship
from datetime import datetime
from extension import db


class Guest(db.Model):
    """客户表（管理端客户管理）"""
    __tablename__ = 'guests'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), comment='客户姓名')
    phone = Column(String(20), unique=True, nullable=False, comment='联系电话')
    id_number = Column(String(30), unique=True, comment='身份证号')
    email = Column(String(50), comment='电子邮箱')
    address = Column(String(255), comment='联系地址')
    vip_level = Column(Integer, default=0, comment='VIP等级')
    total_spent = Column(DECIMAL(10, 2), default=0, comment='累计消费')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    # 反向引用
    reservations = relationship('Reservation', back_populates='guest', lazy=True)
    
    def to_dict(self, include_relations=False):
        """转换为字典"""
        result = {
            'id': self.id,
            'name': self.name,
            'phone': self.phone,
            'id_number': self.id_number,
            'email': self.email,
            'address': self.address,
            'vip_level': self.vip_level,
            'total_spent': float(self.total_spent) if self.total_spent else 0.0,
            'createdAt': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updatedAt': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
        
        # 如果包含关联对象
        if include_relations:
            if self.reservations:
                result['reservations'] = [res.to_dict() for res in self.reservations]
        
        return result
    
    @classmethod
    def from_dict(cls, data):
        """从字典创建实例"""
        return cls(
            name=data.get('name'),
            phone=data.get('phone'),
            id_number=data.get('id_number'),
            email=data.get('email'),
            address=data.get('address'),
            vip_level=data.get('vip_level', 0),
            total_spent=data.get('total_spent', 0)
        )
    
    def update_from_dict(self, data):
        """从字典更新实例"""
        if 'name' in data:
            self.name = data['name']
        if 'phone' in data:
            self.phone = data['phone']
        if 'id_number' in data:
            self.id_number = data['id_number']
        if 'email' in data:
            self.email = data['email']
        if 'address' in data:
            self.address = data['address']
        if 'vip_level' in data:
            self.vip_level = data['vip_level']
        if 'total_spent' in data:
            self.total_spent = data['total_spent']
        return self

